package core.lib;

import java.net.URI;
import java.util.Hashtable;
import java.util.LinkedList;

import core.lib.interfaces.ExternalRequestAgent;
import core.lib.interfaces.ICRequestHandler;
import core.lib.model.CoreRequest;
import core.lib.tools.CoreLog;

public class CoreRequestDispatcher
{
	private Hashtable<String, LinkedList<ICRequestHandler>> mRegisteredHandlers = new Hashtable<String, LinkedList<ICRequestHandler>>();
	private ExternalRequestAgent mExternalDispatcher;

	public void registerCoreRequestHandler(String host, ICRequestHandler handler)
	{
		synchronized (mRegisteredHandlers)
		{
			LinkedList<ICRequestHandler> handlers = mRegisteredHandlers.get(host);

			if (handlers == null)
			{
				handlers = new LinkedList<ICRequestHandler>();
				mRegisteredHandlers.put(host, handlers);
			}

			handlers.add(handler);
		}
	}

	protected void unregisterCoreRequestHandler(String host, ICRequestHandler handler)
	{
		synchronized (mRegisteredHandlers)
		{
			LinkedList<ICRequestHandler> handlers = mRegisteredHandlers.get(host);

			if (handlers == null)
			{
				return;
			}

			handlers.remove(handler);
		}
	}

	public void sendCoreRequest(CoreRequest req)
	{
		URI targetURI = req.getURI();

		if (!CoreConfig.URI_GLOBAL_SCHEME.equals(targetURI.getScheme()))
		{
			if (mExternalDispatcher != null)
			{
				mExternalDispatcher.handlerRequest(req);
			}
			else
			{
				CoreLog.log(CoreLog.LEVEL_ERROR, CoreConstants.CORE_TAG, "No external request handler for unknown request!");
			}
		}
		else
		{
			String host = targetURI.getHost();
			synchronized (mRegisteredHandlers)
			{
				LinkedList<ICRequestHandler> handlers = mRegisteredHandlers.get(host);
				if (handlers != null)
				{
					for (ICRequestHandler handler : handlers)
					{
						handler.handleRequest(req);
					}
				}
			}
		}
	}

	public void setExternalDispatcher(ExternalRequestAgent e)
	{
		mExternalDispatcher = e;
	}
}
